'use strict'

//new
let models = require('../models');
let menus = require('../../config/menus');
let fs = require('fs');
let lib = {
    util: require('../lib/util'),
    menus: require('../lib/menus')
};
let counter = require('../services/report')

let AttendanceStatus = models.AttendanceStatus;
let Attendance = models.Attendance;
let AttendanceReportCache = models.AttendanceReportCache;

let SchoolDao = models.SchoolDao;
let AttendanceReportCacheDao = models.AttendanceReportCacheDao;


let FestivalStatus = models.FestivalStatus;
let Festival = models.Festival;
let FestivalTip = models.FestivalTip;

let NatureClassDao = models.NatureClassDao;
let UserDao = models.UserDao;
let TeacherDao = models.TeacherDao;

let roleService = require('../services/role');
let teacherService = require('../services/teacher');
let checkTimeSetService = require('../services/checktimeset');
let attendanceService = require('../services/attendance');
let reportService = require('../services/report');
let trackService = require('../services/track');
let schoolService = require('../services/school');
let festivalTipService = require('../services/festivaltip');

let viewIndex = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        res.render('public/main', {
            basePath: '',
            title: '首页',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'index',
            selectedMenu: 'index',
            leader: leader,
            user: leader
        });
    }
};

let viewStudentList = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        res.render('public/main', {
            basePath: '',
            title: '学生信息',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'basic_data',
            selectedMenu: 'students',
            leader: leader,
            user: leader,
            school: leader.managedSchool
        });
    }
};

let viewClassList = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        leader.managedSchool.grades.forEach(grade => {
            grade.natureClasses.forEach(natureClass => {
                natureClass.teachers = teacherService.getTeachersOfNatureClass(natureClass);
            });
        });

        res.render('public/main', {
            basePath: '',
            title: '学生信息',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'basic_data',
            selectedMenu: 'classes',
            leader: leader,
            user: leader,
            school: leader.managedSchool
        });
    }
};

//let viewAttendanceReport = {
//    login: true,
//    privileges: [ 'leader' ],
//    handler(req, res) {
//        let user = req.session.login.user;
//        let leader = teacherService.getTeacherByUserId(user.id);
//        let school = leader.managedSchool;
//
//        let queryPeriod = req.query.period;
//        let queryType = req.query.type;
//        let queryId = req.query.id;
//
//        let term = schoolService.getCurrentTerm(school);
//        if ( !term ) {
//            res.render('leader/attendance/report', {
//                basePath: '',
//                statisticsList: []
//            });
//
//            return;
//        }
//
//        let periods = [];
//        if ( queryPeriod == 'week' ) {
//            periods = reportService.generateWeeksInTerm(term);
//        }
//        else if ( queryPeriod == 'month' ) {
//            periods = reportService.generateMonthsInTerm(term);
//        }
//        else {
//            periods = reportService.generateDaysInTerm(term);
//        }
//
//        let renderContent = {
//            basePath: '',
//            lib: lib,
//            period: queryPeriod
//        };
//        if ( queryType == 'school' ) {
//            reportService.calcSchoolStatistics(school, periods);
//            renderContent.peopleCount = school.peopleCount;
//            renderContent.statisticsList = school.statisticsList;
//        }
//        else if ( queryType == 'grade' ) {
//            let grade = school.grades.find(grade => {
//                return grade.id == queryId
//            });
//
//            reportService.calcGradeStatistics(grade, periods);
//            renderContent.peopleCount = grade.peopleCount;
//            renderContent.statisticsList = grade.statisticsList;
//        }
//        else if ( queryType == 'class' ) {
//            let natureClass = NatureClassDao.findOne({
//                id: queryId
//            });
//
//            reportService.calcNatureClassStatistics(natureClass, periods);
//            renderContent.peopleCount = natureClass.peopleCount;
//            renderContent.statisticsList = natureClass.statisticsList;
//        }
//
//        res.render('leader/attendance/report', renderContent);
//    }
//};

let viewAttendanceReport = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let school = teacher.managedSchool;

        let queryPeriod = req.query.period;
        let queryType = req.query.type;
        let queryId = req.query.id;

        if(queryType === 'school'){
            queryId = school.id;
        }


        let term = schoolService.getCurrentTerm(school);
        if ( !term ) {
            res.render('leader/attendance/report', {
                basePath: '',
                statisticsList: []
            });

            return;
        }

        let periods = [];
        if ( queryPeriod == 'week' ) {
            periods = reportService.generateWeeksInTerm(term);
        }
        else if ( queryPeriod == 'month' ) {
            periods = reportService.generateMonthsInTerm(term);
        }
        else {
            periods = reportService.generateDaysInTerm(term);
        }

        let renderContent = {
            basePath: '',
            lib: lib,
            period: queryPeriod
        };

        let attendanceScope = {
            'school':0,
            'grade':1,
            'class':2
        };

        let attendanceInfo = new Array();
        periods.forEach(period=>{
            let info = counter.countPeriodReport(period.startTime,period.endTime,attendanceScope[queryType],queryId);
            console.log(info);
            attendanceInfo.push({
                startTime:period.startTime,
                endTime:period.endTime,
                info:info.toObject({recursive:true})
            });
            console.log(period.endTime);
        });

        renderContent.statisticsList = attendanceInfo;
        //renderContent.peopleCount = 10;

        //res.json({
        //    successful:true,
        //    info:attendanceInfo
        //});

        res.render('leader/attendance/report', renderContent);
    }
};

let viewDailyReport = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let school = leader.managedSchool;
        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            //grade.statistics = attendanceService.emptyStatistics();
            //grade.natureClasses.forEach(natureClass => {
            //    natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
            //    attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            //});
            //attendanceService.combineStatistics(school.statistics, grade.statistics);
            //
            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'attendance',
            selectedMenu: 'daily_report',
            leader: leader,
            user: leader,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let viewWeekReport = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let school = leader.managedSchool;
        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            //grade.statistics = attendanceService.emptyStatistics();
            //grade.natureClasses.forEach(natureClass => {
            //    natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
            //    attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            //});
            //attendanceService.combineStatistics(school.statistics, grade.statistics);

            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'attendance',
            selectedMenu: 'week_report',
            leader: leader,
            user: leader,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let viewMonthReport = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let school = leader.managedSchool;
        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            //grade.statistics = attendanceService.emptyStatistics();
            //grade.natureClasses.forEach(natureClass => {
            //    natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
            //    attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            //});
            //attendanceService.combineStatistics(school.statistics, grade.statistics);

            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'attendance',
            selectedMenu: 'month_report',
            leader: leader,
            user: leader,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let viewSearchAttendance = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let school = leader.managedSchool;

        let startTime = new Date(Number(req.query.start));
        let endTime = new Date(Number(req.query.end));
    
        if ( !req.query.start || !req.query.end ) {
            let time = new Date();

            startTime = new Date(time.getFullYear(), time.getMonth(), time.getDate());
            endTime = new Date(time.getFullYear(), time.getMonth(), time.getDate());

            startTime.setMinutes(startTime.getMinutes() - 1);
            endTime.setDate(endTime.getDate() + 1);
            endTime.setMinutes(endTime.getMinutes() - 1);
        }

        let gradeId = req.query.grade;
        let natureClassId = req.query.nature_class;

        let classes = [];
        let grades = school.grades;
        if ( gradeId ) {
            grades = grades.filter(grade => grade.id == gradeId);
        }

        grades.forEach(grade => {
            classes = classes.concat(grade.natureClasses);
        });

        if ( natureClassId ) {
            classes = classes.filter(natureClass => natureClass.id == natureClassId);
        }

        classes.forEach(natureClass => {
            natureClass.statisticsList = 
                attendanceService.getStatisticsOfNatureClass(natureClass, startTime, endTime);
            natureClass.totalStatistics = attendanceService.emptyStatistics();
            natureClass.statisticsList.forEach(statistics => {
                attendanceService.combineStatistics(natureClass.totalStatistics, statistics);
            });

            natureClass.attendances = 
                attendanceService.getAttendancesOfNatureClass(natureClass, startTime, endTime);
            console.log(natureClass.attendances.length);
        });

        res.render('public/main', {
            leader: leader,
            title: '考勤查询',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'attendance',
            selectedMenu: 'search',
            user: leader,
            grades: school.grades,
            classes: classes,
            roleName: 'leader',
            basePath: '',
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let viewManageDevice = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        let startTime = new Date(Number(req.query.start));
        let endTime = new Date(Number(req.query.end));

        if ( !req.query.startTime || !req.query.endTime ) {
            let date = new Date();
            let startTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, -1);
            let endTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 24, -1);
        }

        let rawAttendances = [];

        let options = {};
        if ( 'type' in req.query ) {
            options.type = req.query.type;
        }
        if ( 'device' in req.query && req.query.device != '0' ) {
            options.device = req.query.device;
        }
        else {
            options.device = {
                $in: leader.managedSchool.devices.map(device => device.id)
            };
        }
        rawAttendances = attendanceService.getRawAttendancesOfDevice(startTime, endTime, options)
            .sort((rawAttendance1, rawAttendance2) => {
                return rawAttendance2.time.getTime() - rawAttendance1.time.getTime();
            });

        console.log(rawAttendances.length);

        res.render('public/main', {
            leader: leader,
            title: '设备管理',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'device',
            selectedMenu: 'manage',
            user: leader,
            basePath: '',
            lib: lib,
            rawAttendances: rawAttendances
        });
    }
};

let CheckTimeSetTypes = [ 'weekdays', 'saturday', 'sunday' ];

let actionTimeSetting = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let schoolCheckTimeSet = leader.managedSchool.checkTimeSet;
        let festivals = leader.managedSchool.festivals;
        let festivalTips = festivalTipService.getAvaliableFestivalTips();
        let grades = leader.managedSchool.grades;

        res.json({
            successful: true,
            leader: {
                name: leader.name
            },
            schoolCheckTimeSet: schoolCheckTimeSet.toObject({
                recursive: true
            }),
            grades: grades.map(grade => {
                return {
                    name: grade.name,
                    checkTimeSet: grade.checkTimeSet.toObject({
                        recursive: true
                    })
                };
            }),
            festivals: Festival.toObjectArray(festivals, {
                recursive: true
            }),
            festivalTips: FestivalTip.toObjectArray(festivalTips, {
                recursive: true
            })
        });
    }
};

let actionLeaderInfo = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        res.json({
            successful: true,
            leader: {
                name: leader.name,
                managedSchool: {
                    id: leader.managedSchool.id
                }
            }
        });
    }
};

let viewCheckTimes = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        res.render('public/main', {
            leader: leader,
            title: '考勤时间设置',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'system',
            selectedMenu: 'check_time',
            user: leader,
            basePath: ''
        });
    }
};

let viewFestivals = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        res.render('public/main', {
            leader: leader,
            title: '考勤时间设置',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'system',
            selectedMenu: 'festival',
            user: leader,
            basePath: ''
        });
    }
};

let viewTerms = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        res.render('public/main', {
            leader: leader,
            title: '考勤时间设置',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'system',
            selectedMenu: 'term',
            user: leader,
            basePath: ''
        });
    }
};

let viewPrivileges = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);

        let teachers = [];
        leader.managedSchool.grades.forEach(grade => {
            grade.natureClasses.forEach(natureClass => {
                let natureClassTeachers = teacherService.getTeachersOfNatureClass(natureClass);
                // 一个老师可能关联很多班级，需要去重
                natureClassTeachers.forEach(teacher => {
                    if ( !teachers.find(existedTeacher => existedTeacher.id == teacher.id) ) {
                        teachers.push(teacher);
                    }
                });
            });
        });

        res.render('public/main', {
            leader: leader,
            title: '权限管理',
            menus: lib.menus.generateMenus(user),
            role: 'leader',
            selectedTab: 'user',
            selectedMenu: 'privileges',
            user: leader,
            basePath: '',
            teachers: teachers
        });
    }
};

let actionGrantLeader = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let teacherUserId = req.body.user.id;
        let teacher = teacherService.getTeacherByUserId(teacherUserId);

        teacher.managedSchool = leader.managedSchool;
        teacher.user.role = roleService.getRoleByName('leaderTeacher');
        UserDao.update(teacher.user);
        TeacherDao.update(teacher);

        res.json({
            successful: true
        });
    }
};

let actionCancelLeader = {
    login: true,
    privileges: [ 'leader' ],
    handler(req, res) {
        let user = req.session.login.user;
        let leader = teacherService.getTeacherByUserId(user.id);
        let teacherUserId = req.body.user.id;
        let teacher = teacherService.getTeacherByUserId(teacherUserId);

        teacher.user.role = roleService.getRoleByName('teacher');
        UserDao.update(teacher.user);

        res.json({
            successful: true
        });
    }
};

module.exports = {
    viewIndex,
    viewStudentList,
    viewClassList,
    viewDailyReport,
    viewWeekReport,
    viewMonthReport,
    viewAttendanceReport,
    viewSearchAttendance,
    viewManageDevice,
    viewCheckTimes,
    viewFestivals,
    viewTerms,
    viewPrivileges,
    actionTimeSetting,
    actionLeaderInfo,
    actionGrantLeader,
    actionCancelLeader
};
